import 'package:flame/components.dart';
import 'package:flame_tiled/flame_tiled.dart';

import 'CollidableObject.dart';

class MapManager {
  List<TiledObject> wallList = [];

  bool isPassable(double x, double y) {
    final tileX = x; // Assuming each tile is 32x32 pixels
    final tileY = y;
    //print("object ${objectGroup.objects.length}");
    for (final obj in wallList) {
      var xx1 = obj.position.x - 32;
      var xx2 = (obj.position.x + obj.width);
      var yy1 = obj.position.y - 32;
      var yy2 = (obj.position.y + obj.height);
      //print('${x},${y} 位置  ${obj.position}');
      //print('${tileX},${tileY} 位置2  $xx1,$yy1  $xx2,$yy2');
      if ((tileX >= xx1 && tileX <= xx2) && (tileY >= yy1 && tileY <= yy2)) {
        print('${tileX},${tileY} 不可走');
        return false;
      }
      //print('Object class: $className');
    }
    return true; // Assuming 'wall' tiles are not passable
  }

  Future<void> initMap(Component component) async {
    final tiledMap = await TiledComponent.load(
      'l2.tmx',
      Vector2.all(32),
    );
    component.add(tiledMap);

    // 获取对象层
    final objectGroup = tiledMap.tileMap.getLayer<ObjectGroup>('Objecter');
    print('tiledMap.tileMap: ${objectGroup}');

    if (objectGroup != null) {
      for (final obj in objectGroup.objects) {
        final className = obj.class_; // 获取对象的 class 属性
        if (className == "Wall") {
          component.add(CollidableObject(obj.x, obj.y, obj.width, obj.height));
          wallList.add(obj);
        }
        //print('Object class: $className');
      }
    } else {
      //print('Object layer not found');
    }
  }
}
